package com.pet.server.ext.sms;

import java.sql.PreparedStatement;
import java.sql.Connection;
import java.util.LinkedList;


public class PushWrapper {

    public static void push(Connection conn, int accountId, String cid, String title, String msgContent, String transContent) throws Exception {
    	saveIntoDb(conn, accountId, title, msgContent, transContent);
    	if (cid != null && cid.length() > 0) {
    		push2Phone(accountId, cid, title, msgContent, transContent);
    	}
    }
    
    private static void saveIntoDb(Connection conn, int accountId, String title, String msgContent, String transContent) throws Exception {
    	String sqlTemplate = "INSERT INTO message_history (account_id, title, msg_content, trans_content) VALUES (?,?,?,?)";
		PreparedStatement stat = conn.prepareStatement(sqlTemplate);
		stat.setInt(1, accountId);
		stat.setString(2, title);
		stat.setString(3, msgContent);
		stat.setString(4, transContent);
		stat.execute();
		stat.close();
    }
    
    private static void push2Phone(int accountId, String cid, String title, String msgContent, String transContent) throws Exception {
    	pusher.schedulePush(accountId, cid, title, msgContent, transContent);
    }
    
    private static class AsyncPusher implements Runnable{
    	
    	public void schedulePush(final int accountId, final String cid, final String title, final String msgContent, final String transContent) {
    		synchronized(this) {
    			jobList.add(new Runnable() {
    				public void run() {
    			        try {
							PushHelper.push(cid, title, msgContent, transContent);
						} catch (Exception e) {
							//logcat.debug(e);
						}
    				}
    			});
    			if (jobThread == null) {
    				jobThread = new Thread(this);
    				jobThread.start();
    			}
    		}
    	}
    	
    	private void goNext() {
    		synchronized(this) {
    			if (jobList.size() > 0) {
    				job = jobList.removeFirst(); 
    			}else{
    				jobThread = null;
    				job = null;
    			}
    		}
    	}

		public void run() {
			for (goNext(); job != null; goNext()) {
				job.run();
			}
		}
    	
    	private LinkedList<Runnable> jobList = new LinkedList<Runnable>(); 
    	private Thread jobThread = null;
    	private Runnable job = null;
    }
    
    private static AsyncPusher pusher = new AsyncPusher();
}
